﻿#pragma once
#include "Common.h"
template<class T>
class ObjectPool
{
public:
	T* New()
	{
		T* obj = nullptr;
		// 如果⾃由链表有对象，直接取⼀个
		if (_freeList)
		{
			void* next =  *((void**)_freeList);
			obj = (T*)_freeList;
			_freeList = next;
		}
		else
		{
			// 剩余内存不够一个对象大小时，则重新开大块空间
			if (_leftBytes < sizeof(T))
			{
				_leftBytes = 128 * 1024;
				//_memory = (char*)malloc(_leftBytes);
				_memory = (char*)SystemAlloc(_leftBytes >> 13);
				if (_memory == nullptr)
				{
					throw std::bad_alloc();
				}
			}
			obj = (T*)_memory;
			size_t objSize = sizeof(T) < sizeof(void*) ? sizeof(void*) : sizeof(T);
			_memory += objSize;
			_leftBytes -= objSize;
		}
		// 使⽤定位new调⽤T的构造函数初始化
		new(obj)T;
		return obj;
	}
	void Delete(T* obj)
	{
		// 显⽰调⽤的T的析构函数进⾏清理
		obj->~T();
		// 头插到freeList
		*((void**)obj) = _freeList;
		_freeList = obj;
	}
	/*~ObjectPool()
	{
		while (_memory)
		{
			void* next = *(void**)_memory;
			free(_memory);
			_memory = (char*)next;
		}
		_freeList = nullptr;
	}*/
private:
	char* _memory = nullptr; // 指向内存块的指针
	int _leftBytes = 0; // 内存块中剩余字节数
	void* _freeList = nullptr; // 管理还回来的内存对象的⾃由链表
};


